const NodeRSA = require('node-rsa');

class RsaDecryptService {
  publicKey: string;
  key: any;

  constructor() {
    this.publicKey =
      'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDOcJ+zsvqXBQjuySOXsN7xiYEsSIinBVQw+p0FtYkSquEg2seab/0SRJkRA3Nqg5Lq7maWD5sMuxWtjqt1dQeMR1Newv4Ttw4neQBuP2Au5jd+t/hvbpIAB261+vYsw2z88LZB6HqbfYRFovJ5PaEDk7lawlmqYjPUheGQIaa/hQIDAQAB';
    this.key = this.initKey();
  }

  initKey() {
    try {
      const publicKeyBuffer = Buffer.from(this.publicKey, 'base64');
      const key = new NodeRSA();
      key.importKey(publicKeyBuffer, 'pkcs8-public-der');
      return key;
    } catch (error) {
      throw new Error(`初始化公钥失败: ${error.message}`);
    }
  }

  /**
   * 分段解密
   */
  decrypt(data: string): string {
    try {
      const encryptedData = Buffer.from(data, 'base64');
      const chunkSize = 128;
      const decryptedChunks = [];

      for (let offset = 0; offset < encryptedData.length; offset += chunkSize) {
        const chunk = encryptedData.subarray(
          offset,
          Math.min(offset + chunkSize, encryptedData.length)
        );
        const decryptedChunk = this.key.decryptPublic(chunk);
        decryptedChunks.push(decryptedChunk);
      }

      return Buffer.concat(decryptedChunks).toString('utf8');
    } catch (error) {
      throw new Error(`解密失败: ${error.message}`);
    }
  }

  /**
   * 验证公钥是否有效
   */
  validateKey(): boolean {
    try {
      const testData = 'test';
      const encrypted = this.key.encrypt(testData, 'base64');
      const decrypted = this.decrypt(encrypted);
      return decrypted === testData;
    } catch (error) {
      return false;
    }
  }
}

export default RsaDecryptService;
